const api = require('../../../config/api.js');
const user = require('../../../services/user.js');
const app = getApp();
let that;
Page({
  data: {
    version: app.globalData.version,
    username: '',
    password: '',
    code: '',
    loginErrorCount: 0,
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo')
  },
  onLoad: function (options) {
    // 页面初始化 options为页面跳转所带来的参数
    // 页面渲染完成
    that = this;
  },
  onReady: function () {

  },
  onShow: function () {
    // 页面显示
  },
  onHide: function () {
    // 页面隐藏
  },
  onUnload: function () {
    // 页面关闭
  },
  startLogin: function () {
    if (that.data.password.length < 1 || that.data.username.length < 1) {
      wx.showModal({
        title: '错误信息',
        content: '请输入用户名和密码',
        showCancel: false
      });
      return false;
    }

    wx.request({
      url: api.AuthLoginByWeixin,
      data: {
        username: that.data.username,
        password: that.data.password
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        console.log(res)
        if(res.data.code == 200){
          that.setData({
            'loginErrorCount': 0
          });
          wx.setStorage({
            key:"token",
            data: res.data.data.token,
            success: function(){
              wx.switchTab({
                url: '/pages/ucenter/index/index'
              });
            }
          });
        }
      }
    });
  },
  bindUsernameInput: function (e) {
    this.setData({
      username: e.detail.value
    });
  },
  bindPasswordInput: function (e) {
    this.setData({
      password: e.detail.value
    });
  },
  bindCodeInput: function (e) {
    this.setData({
      code: e.detail.value
    });
  },
  clearInput: function (e) {
    switch (e.currentTarget.id) {
      case 'clear-username':
        this.setData({
          username: ''
        });
        break;
      case 'clear-password':
        this.setData({
          password: ''
        });
        break;
      case 'clear-code':
        this.setData({
          code: ''
        });
        break;
    }
  }, 
  getUserInfo: function (e) {
    console.log('pages/auth/login/login.js', e)
    //授权登陆
    user.loginByWeixin().then(res => {
      app.globalData.Refresh = true;
      wx.switchTab({
        url: '/pages/ucenter/index/index'
      });
    }).catch((err) => {
      console.log('pages/auth/login/login.js',err)
    });
  },
})